package compilers.node;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import compilers.Node;
import compilers.condition.Return;
import compilers.stmt.If;
import compilers.stmt.Var;
import compilers.stmt.While;
import compilers.table.MemScope;
import compilers.types.Type;

public class Stmt extends Program {

	Vector<Node> fNodes = new Vector<Node>();
	private int fVarCount = 0;
	
	public void addNode(Node fNode) {
		if (fNode instanceof If) {
			If n = (If)fNode;
			if (n.getfStatement1() != null)
				setfVarCount(getfVarCount() + n.getfStatement1().getfVarCount());
			if (n.getfStatement2() != null)
				setfVarCount(getfVarCount() + n.getfStatement2().getfVarCount());
		} else if (fNode instanceof While) {
			While n = (While)fNode;
			setfVarCount(getfVarCount() + n.getfStatement().getfVarCount());
		}
		if (fNode instanceof VarList) {
			VarList v = (VarList)fNode;
			for (int i = 0; i < v.fVars.size(); i++) {
				v.fVars.get(i).setInit();
				fNodes.add(v.fVars.get(i));
				setfVarCount(getfVarCount() + v.fVars.get(0).getfExpressions().size());
			}
		} else {
			fNodes.add(fNode);
		}
		if (fNode instanceof Var) {
			Var tmp = (Var)fNode;
			if (!tmp.getfType().getfIdentifier().getIndices(null).isEmpty()) {
				fVarCount++;
			}
		}
	}
	
	public void print(int tab) {
		for (int i=1;i<=tab;i++){System.out.print("\t");}System.out.print("|-");
		System.out.println("Stmt");
		Enumeration<Node> enumeration = fNodes.elements();
		while(enumeration.hasMoreElements()){
			((Node) enumeration.nextElement()).print(tab+1);
		} 
	}

	public void generate(BufferedWriter writer, MemScope scope) throws IOException {
		Enumeration<Node> enumeration = fNodes.elements();
		while(enumeration.hasMoreElements()){
			Node n = ((Node) enumeration.nextElement());
			n.generate(writer, scope);
		} 
	}

	public int getfVarCount() {
		return fVarCount;
	}

	public void setfVarCount(int fVarCount) {
		this.fVarCount = fVarCount;
	}
	
	public void setfResReturn(Type res){
		Enumeration<Node> enumeration = fNodes.elements();
		while(enumeration.hasMoreElements()){
			Node n = ((Node) enumeration.nextElement());
			if (n instanceof Return) {
				((Return)n).setfRes(res);
			}
		} 
	}

}
